package com.basic.hellorabbit.controller;

import com.basic.hellorabbit.util.SendSmsUtil;
import com.basic.hellorabbit.util.VerificationCode;
import com.google.gson.Gson;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
* @Description:    短信
* @Author:         Joe
* @CreateDate:     2020/3/21 16:31
*/
@Controller
public class SmsController {


    @Autowired
    private SendSmsUtil sendSmsUtil;

    @Data
    public static class SmsData{
        String code;

        public SmsData(String code) {
            this.code = code;
        }
    }

    /**
     * 跳转到短信测试页面
     * @return
     */
    @RequestMapping(value = "/toSms",method = RequestMethod.GET)
    public String toSms(){
        return "sms";
    }

    /**
     * 发送验证码
     * @param PhoneNumbers 手机号
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/sendSms/{PhoneNumbers}",method = RequestMethod.GET)
    public String sendSms(@PathVariable String PhoneNumbers, HttpServletRequest request){
        HttpSession session = request.getSession();
        //随机生成验证码
        String numeral = VerificationCode.getNumeral();
        SmsData smsData = new SmsData(numeral);
        Gson gson = new Gson();
        System.out.println(gson.toJson(smsData));
        String code = gson.toJson(smsData);
        String information = sendSmsUtil.aliSendSms(PhoneNumbers, code);
        session.setAttribute(PhoneNumbers,numeral);
        session.setMaxInactiveInterval(3 * 60);
        if(information.equals("ok")){
            return "成功发送给"+PhoneNumbers+";验证码是"+numeral;

        }
            return "失败了"+PhoneNumbers;

    }

    /**
     * 验证
     * @param PhoneNumbers
     * @param code
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/yanSms",method = RequestMethod.POST)
    public String yanSms(String PhoneNumbers, String code,HttpServletRequest request){
        HttpSession session = request.getSession();
        String ycode = (String) session.getAttribute(PhoneNumbers);
        if(ycode.equals(code)){
            return PhoneNumbers+"验证成功";
        }

        return PhoneNumbers+"验证失败";

    }



}
